<template>
  <div>
    <panel title="单据查询条件" :enableToggle="false">
      <Form ref="frmParams" :model="form" :label-width="60">
        <FormItem label="Host">
          <Row>
            <Col span="12">
              <Select v-model="form.env">
                <Option v-for="item of form.envs" :value="item.value">{{ item.name }}</Option>
              </Select>
            </Col>
            <Col span="6">
              <ButtonGroup shape="circle">
                <Button @click.native="search(1, 'research')" type="primary" icon="ios-search">查询</Button>
                <Button type="success" icon="md-copy" @click.native="onCopyResult">复制结果</Button>
              </ButtonGroup>
            </Col>
          </Row>
        </FormItem>
      </Form>
    </panel>
    <div class="section clear" style="margin-top: 10px">
      <Table border stripe :highlight-row="true" :height="detailHeight" :columns="columns" :data="datas">
        <template slot-scope="{ row, index }" slot="index">{{ offsets + index + 1 }}</template>
        <template #original="{row, index}">
          <Tooltip :content="row.OriginalPageUrl" placement="top-start" :transfer="true" max-width="400">
            <Button type="primary" size="small" shape="circle" @click.native="getOriginalPageUrl(row)" :long="true" target="_blank">访问</Button>
          </Tooltip>
        </template>
        <template #page-url="{row}">
          <Tooltip :content="row.PageUrl" placement="top-start" :transfer="true" max-width="400">
            <Button type="info" size="small" :to="row.PageUrl" shape="circle" :long="true" target="_blank">访问</Button>
          </Tooltip>
        </template>
        <template #loaded-date="{row}">{{ row.LoadedDateTime | datetime }}</template>
        <template #completed-date="{row}">{{ row.CompletedDateTime | datetime }}</template>
      </Table>
      <Page ref="pager" :total="total" :page-size="20" show-total show-elevator @on-change="search" style="margin-top:5px;" />
    </div>
  </div>
</template>
<script>
import md5 from 'js-md5';

export default {
  data() {
    return {
      form: {
        env: 'uat',
        envs: [
          { name: '正式环境', value: 'prod' },
          { name: 'UAT&测试环境', value: 'uat' }
        ]
      },
      total: 0,
      datas: [],
      offsets: 0,
      detailHeight: 400,
      columns: [
        {
          title: '序号',
          slot: 'index',
          align: 'center',
          width: 80
        },
        {
          title: '请求页',
          key: 'OriginalPageUrl',
          slot: 'original',
          width: 100
        },
        {
          title: '嵌套页',
          key: 'PageUrl',
          width: 100,
          slot: 'page-url'
        },
        {
          title: '加载时间',
          key: 'LoadedDateTime',
          width: 180,
          align: 'center',
          slot: 'loaded-date'
        },
        {
          title: '加载完成时间',
          key: 'CompletedDateTime',
          width: 180,
          align: 'center',
          slot: 'completed-date'
        },
        {
          title: '耗时(秒)',
          key: 'IntervalSeconds',
          width: 100
        }
      ]
    };
  },
  methods: {
    search(index = 1, type) {
      if (type == 'research') {
        this.$refs.pager.currentPage = 1;
      }

      this.$http.post(`/api/iworkflow/${this.form.env}/statistics/pageloads`, { pageIndex: index, pageSize: 20 }).then(rs => {
        this.datas = rs.datas;
        this.total = rs.total;
        this.offsets = this.$refs.pager.currentPageSize * (index - 1);
      });
    },
    getOriginalPageUrl(item) {
      let host = 'https://nwf.capitaland.com.cn';

      if (this.form.env != 'prod') {
        host = 'https://nwfuat.capitaland.com.cn';
      }

      let params = new Map();
      let urls = item.OriginalPageUrl.split('?');
      let queryStrings = (urls[1] || '').split('&');

      queryStrings.forEach(item => {
        let keyValue = item.split('=');

        params.set(keyValue[0], keyValue[1]);
      });

      params.set('UserId', item.UserId);
      params.set('accessUserId', 'dc\\k2dev01');
      params.set('accessUserName', 'k2dev01');
      params.set('timestamp', parseInt(new Date().getTime() / 1000));

      let temp = '';
      let sortedKeys = [...params.keys()].sort((a, b) => a.localeCompare(b));

      sortedKeys.forEach(item => {
        temp += `${item}=${params.get(item)}&`;
      });

      params.set('token', md5(temp.substr(0, temp.length - 1)).toUpperCase());

      let newUrl = urls[0] + '?';

      for (let [key, value] of params) {
        newUrl += `${key}=${value}&`;
      }

      newUrl = newUrl.substr(0, newUrl.length - 1);

      window.open(`${host}${newUrl}`, '_blank');
    },
    ResizeDetailPanel(area) {
      this.detailHeight = area.height - 160;
    }
  },
  mounted() {
    this.search();
    let area = this.getClientArea();

    this.ResizeDetailPanel(area);

    this.$bus.on('windowResizeChanged', client => {
      this.ResizeDetailPanel(client);
    });
  }
};
</script>
<style lang="less"></style>
